package com.demo.android.bmi;

import java.text.DecimalFormat;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.KeyEvent;
import android.view.Menu;

import android.widget.*;
import android.view.View.*;
import android.view.View;

public class Bmi extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_bmi);

		// listen for button clicks
		Button button = (Button) findViewById(R.id.submit);
		button.setOnClickListener(calcBMI);

	}

	// 实现接口
	private OnClickListener calcBMI = new OnClickListener() {

		public void onClick(View v) {

			try {
				DecimalFormat nf = new DecimalFormat("0.00");
				EditText fieldheight = (EditText) findViewById(R.id.height);
				EditText fieldweight = (EditText) findViewById(R.id.weight);
				double height = Double.parseDouble(fieldheight.getText()
						.toString()) / 100;
				double weight = Double.parseDouble(fieldweight.getText()
						.toString());
				double BMI = weight / (Math.pow(height, 2));

				TextView result = (TextView) findViewById(R.id.result);
				result.setText("Your BMI is " + nf.format(BMI));

				TextView fieldsuggest = (TextView) findViewById(R.id.suggest);

				if (BMI > 25) {
					fieldsuggest.setText(R.string.advice_heavy);
				} else if (BMI < 20) {
					fieldsuggest.setText(R.string.advice_light);
				} else {
					fieldsuggest.setText(R.string.advice_average);
				}
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(), "输入错误！",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.bmi, menu);
		return true;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode==KeyEvent.KEYCODE_BACK){
			
			new AlertDialog.Builder(this)
			    .setMessage(R.string.msg_yn)
			    .setNegativeButton(R.string.msg_cancel,
			    		new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								
							}
						})
				.setPositiveButton(R.string.msg_ok,
						new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								finish();
							}
						})
			    .show();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		android.os.Process.killProcess(android.os.Process.myPid());
	}

}
